package pers.cj.pdos.controller;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.constant.OrderType;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.OrderRule;
import pers.cj.pdos.entity.ProviderType;
import pers.cj.pdos.excel.ExcelCustom;
import pers.cj.pdos.excel.ExcelProvider;
import pers.cj.pdos.excel.ExcelProviderListener;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.CustomVo;
import pers.cj.pdos.vo.ProviderVo;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 数据库表格操作
 */
@Controller
@RequestMapping("/provider")
public class ProviderExcelController extends BaseController {
    @Autowired
    IProviderTypeService providerTypeService;
    @Autowired
    IProviderService providerService;
    @Autowired
    IOrderRuleService orderRuleService;

    @RequiresPermissions("provider:import")
    @RequestMapping("/providerImport")
    public String providerImport() {
        return "provider/providerImport";
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("provider:export")
    @RequestMapping("/provider/export")
    public ResponseData export(String status,
                               String search,
                               String providerTypeId,
                               String no,
                               String name,
                               String unitTel,
                               String phone,
                               String contacts,
                               String remark) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<ProviderVo> providerVoList = providerService.listVoPage(company.getId(),
                null,
                null,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                providerTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getProviderStoreId(userVo, null));

        String fileName = "供应商列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelProvider.class);
            sheet1.setSheetName("供应商信息");
            writer.write(genExcelList(providerVoList), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("列表导出失败");
        }
    }

    private List<ExcelProvider> genExcelList(List<ProviderVo> providerVoList) {
        List<ExcelProvider> list = new ArrayList<>();
        for (ProviderVo providerVo : providerVoList){
            ExcelProvider excel = new ExcelProvider();
            excel.setType(providerVo.getProviderType().getName());
            excel.setNo(providerVo.getNo());
            excel.setName(providerVo.getName());
            excel.setUnitTel(providerVo.getUnitTel());
            excel.setContacts(providerVo.getContacts());
            excel.setPhone(providerVo.getPhone());
            excel.setTax(providerVo.getTax());
            excel.setEmail(providerVo.getEmail());
            excel.setCode(providerVo.getCode());
            excel.setWechat(providerVo.getWechat());
            excel.setQq(providerVo.getQq());
            excel.setAddress(providerVo.getAddress());
            excel.setStatus(providerVo.getStatus()==1 ? "正常" : "停用");
            excel.setRemark(providerVo.getRemark());
            list.add(excel);
        }
        return list;
    }

    @ResponseBody
    @RequiresPermissions("provider:import")
    @RequestMapping(value = "/provider/importProvider", method = RequestMethod.POST)
    public ResponseData importProvider(MultipartFile excelFile) {
        Company company = getCompany();
        try {
            if(excelFile == null){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            //文件名
            String uploadName= excelFile.getOriginalFilename();
            if (Utils.isEmpty(uploadName)) {
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }
            String type = uploadName.substring(uploadName.lastIndexOf(".")+1);
            if (!"xlsx".equals(type)){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            InputStream inputStream = excelFile.getInputStream();
            ExcelProviderListener listener = new ExcelProviderListener();
            listener.init(company,getLoginUserVo());

            TimeLog.getInstance().begin(getClass(),"读取");

            ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
            excelReader.read(new Sheet(1,1, ExcelProvider.class));
            TimeLog.getInstance().end();

            TimeLog.getInstance().begin(getClass(),"保存数据");
            if (!Utils.isEmpty(listener.getProviderList())) {
                providerService.insert(listener.getProviderList(), listener.getProviderTypeList());
            }
            TimeLog.getInstance().end();

            if (Utils.isEmpty(listener.getDataMsgList())){
                return ResponseData.success(null);
            } else {
                ResponseData responseData = new ResponseData();
                responseData.setCode(3);
                responseData.setMsg("部分供应商未导入成功");
                responseData.setData(listener.getDataMsgList());
                return responseData;
            }
        }  catch (Exception e) {
            return ResponseData.fail("供应商导入失败");
        }

    }




}
